using System;
using System.IO;
using System.Runtime.Serialization;
using Aluetjen.EmailService.Domain.Models.Message;

namespace Aluetjen.EmailService.Domain.Gateways
{
    public class FileShareGateway : IGatewayImpl
    {
        private static int _serialNumber;
        private static readonly object SerialNumberLock = new object();

        private string _fileShare;

        public FileShareGateway()
        {
        }

        public FileShareGateway(string fileShare)
        {
            _fileShare = fileShare;
        }

        public void Configure(string connectionString)
        {
            if(!string.IsNullOrWhiteSpace(connectionString))
            {
                if(!Directory.Exists(connectionString))
                {
                    Directory.CreateDirectory(connectionString);
                }

                _fileShare = connectionString;
            }
        }

        public void Send(MailMessage message)
        {
            int serialNumberForMessage;
            lock(SerialNumberLock)
            {
                serialNumberForMessage = _serialNumber;
                _serialNumber++;
            }

            string messageFilePath = Path.Combine(_fileShare, string.Format("{0:yyyyMMdd_hhmmss}_{1}.xml", DateTime.UtcNow, serialNumberForMessage));

            using (var fileStream = new FileStream(messageFilePath, FileMode.CreateNew, FileAccess.Write))
            {
                var serializer = new DataContractSerializer(typeof (MailMessage));
                serializer.WriteObject(fileStream, message);
            }
        }
    }
}